package server;

import com.oe.servlet.HttpServlet;
import com.oe.servlet.Request;
import com.oe.servlet.Response;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,AppContext> appContextMap;

    public RequestProcessor(Socket socket, Map<String,AppContext> appContextMap) {
        this.socket = socket;
        this.appContextMap = appContextMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();
            //先去掉首个‘/’
            String substringUrl = url.substring(1, url.length());
            int i = substringUrl.indexOf("/");
            String basePath=substringUrl.substring(0,i);
            String  reqUrl = substringUrl.substring(i,substringUrl.length());
            AppContext appContext = appContextMap.get(basePath);
            Map<String, HttpServlet> servletMap = appContext.getServletMap();

            // 静态资源处理
            if(servletMap.get(reqUrl) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(reqUrl);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
